/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2023-10-07     SenyPC       the first version
 */
#include <rtthread.h>
#include <rtdevice.h>

#define DBG_TAG "dev.wdt"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

#define WDT_DEVICE_NAME    "wdt"    /* 看门狗设备名称 */

static rt_device_t dev_wdg;         /* 看门狗设备句柄 */


static void idle_hook(void)
{
    /* 在空闲线程的回调函数里喂狗 */
    rt_device_control(dev_wdg, RT_DEVICE_CTRL_WDT_KEEPALIVE, NULL);
}


int wdt_sample(void)
{
    rt_err_t ret = RT_EOK;
    rt_uint32_t timeout = 2;        /* 溢出时间，单位：秒 */
    char device_name[RT_NAME_MAX]=WDT_DEVICE_NAME;

    /* 根据设备名称查找看门狗设备，获取设备句柄 */
    dev_wdg = rt_device_find(device_name);
    if (!dev_wdg)
    {
        LOG_E("find %s failed!", device_name);
        return RT_ERROR;
    }
    /* 初始化设备 */
    ret = rt_device_init(dev_wdg);
    if (ret != RT_EOK)
    {
        LOG_E("initialize %s failed!", device_name);
        return RT_ERROR;
    }
    /* 设置看门狗溢出时间 */
    ret = rt_device_control(dev_wdg, RT_DEVICE_CTRL_WDT_SET_TIMEOUT, &timeout);
    if (ret != RT_EOK)
    {
        LOG_E("set %s timeout failed!", device_name);
        return RT_ERROR;
    }
    /* 启动看门狗 */
    ret = rt_device_control(dev_wdg, RT_DEVICE_CTRL_WDT_START, RT_NULL);
    if (ret != RT_EOK)
    {
        LOG_E("start %s failed!", device_name);
        return -RT_ERROR;
    }
    /* 设置空闲线程回调函数 */
    rt_thread_idle_sethook(idle_hook);

    LOG_D("dev_uart open sucess.");

    return ret;
}

